import { useState, useEffect } from 'react'
import { Checkbox, Popover, message  } from 'antd'
import { cloneDeep } from 'lodash';
import CommonModal from '@/components/CommonModal'
import CommonLoading from '@/components/CommonLoading';
import { bingWarehouseOp } from '../service'
import styles from '../index.module.less'

//快递绑定仓库弹窗
 const AddWarehouseModal = ({ visible, expressId, warehouseList, handleOk, handleCancel }) => {
  const [loading, setLoading] = useState(false);//loading
  const [list, setList] = useState([]);

   useEffect(()=>{
     if(visible){
      setList(warehouseList)
     }
   },[visible])

  const onOk = async () => {
    const hasChecked = list.some(item => item.checked)
    if(hasChecked){
      const arr = [];
      list.map(item=>{
        if(item.checked){
          arr.push(item.id)
        }
      })
       setLoading(true)
       const { msg, success } = await bingWarehouseOp({
        expressId,
        warehouseIds:arr.join()
       })
       if(success){
         message.success(msg);
         handleOk();
         onCancel();
       }
       setLoading(false)
    }else{
      message.info('请至少选择1个仓库')
    }
  }

  const onCancel = () => {
    handleCancel();
    setList([])
  }

  const handleChange = (val, index) => {
    const arr = cloneDeep(list)
    arr[index]["checked"] = val;
    setList(arr)
  }

  return (
    <CommonModal
       title='添加可用仓库'
       visible={visible}
       onOk={onOk}
       onCancel={onCancel}
    >
      <div className={styles.modalWrapper}>
        {list.map((item, index)=>{
          const { checked, warehouseName } = item
          return (<div className={styles.itemBox} key={item.id}>
            <Checkbox checked={checked} onChange={(e)=>handleChange(e.target.checked,index)}/>&nbsp;&nbsp;
            <Popover content={(<div className='custom-ant-popver-content'>{warehouseName || ''}</div>)}>
               <span className='textOverflowMultiTwo' style={{cursor:'pointer'}}>{warehouseName || ''}</span>
            </Popover>
          </div>)
        })}

      </div>
      <CommonLoading loading={loading} />
    </CommonModal>
  )
}

export default AddWarehouseModal